import re
from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings

from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU
from users import constants
from users.models import User, Address


class SKUSerializer(serializers.ModelSerializer):
    """
    SKU序列化器
    """

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    """
    添加用户浏览历史序列化器
    """
    sku_id = serializers.IntegerField(label="商品SKU编号", min_value=1)

    def validate_sku_id(self, value):
        """
        查看是否有这个商品
        :param value:
        :return:
        """
        try:
            SKU.objects.get(id=value)
        except SKU.DoseNotExist:
            raise serializers.ValidationError('该商品不存在')
        return value

    def create(self, validated_data):
        """
        保存到redis中
        :param validated_data:
        :return:
        """
        sku_id = validated_data['sku_id']
        user_id = self.context['request'].user.id

        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()

        # 存到redis中key的值
        redis_key = 'history_%s' % user_id

        # 去重
        # lrem(name, count, value)
        pl.lrem(redis_key, 0, sku_id)
        # 添加新的记录
        pl.lpush(redis_key, sku_id)

        # 只保存五条纪录 ltrim(name, start, end)
        pl.ltrim(redis_key, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)

        pl.execute()
        return validated_data


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    修改标题序列化器
    """

    class Meta:
        model = Address
        fields = ('title',)


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号码
        :param value:
        :return:
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            return serializers.ValidationError('手机号号码格式错误')
        return value

    def create(self, validated_data):
        """
        把数据保存到数据库中
        :param validated_data:
        :return:
        """
        # 1 从对象中取出user放到validated_data中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class EmailSerializer(serializers.ModelSerializer):
    """
    用户邮箱序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'email')

    def update(self, instance, validated_data):
        """
        更新数据库
        :param instance: 传过来的user
        :param validated_data:
        :return:
        """
        email = validated_data['email']
        instance.email = email
        instance.save()

        # 生成激活url连接
        url = instance.generate_verify_email_url()
        # 用celery发送邮件
        send_verify_email.delay(email, url)
        return instance


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class CreateUserSerializer(serializers.ModelSerializer):
    """
    创建用户序列化器
     username, password, password2, sms_code, mobile, allow
    """
    # 1 先创建 password2, sms_code, allow 序列化字段
    password2 = serializers.CharField(label="确认密码", write_only=True)
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    allow = serializers.CharField(label="同意协议", write_only=True)
    # 增加 token 字段
    token = serializers.CharField(label='登录状态token', read_only=True)

    class Meta:
        model = User
        fields = ("id", "username", "password", "password2", "sms_code", "mobile", "allow", "token")
        # 2 给username, password增加约束, 给前段返回error_message
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5,
                'error_messages': {
                    'max_length': '仅允许5-20个字符的用户名',
                    'min_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                "write_only": True,
                'max_length': 20,
                'min_length': 8,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 3 校验手机号
    def validate_mobile(self, value):
        """
        验证手机号码
        :param value:
        :return:
        """
        if not re.match(r'^1[345789]\d{9}$', value):
            raise serializers.ValidationError('手机号码格式不正确')
        return value

    # 4 检验是用户否同意
    def validate_allow(self, value):
        """
        检验用户是否同意协议
        :param value:
        :return:
        """
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    # 5 判断两次密码是否一致
    def validate(self, attrs):
        """
        判断两次密码是否一致
        判断短信验证码是否正确,过期
        :param attrs:
        :return:
        """
        password = attrs['password']
        password2 = attrs['password2']
        if password != password2:
            raise serializers.ValidationError('两次密码不一致')

        # 6 校验短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = attrs['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return attrs

    # 7给密码加密重写create方法
    def create(self, validated_data):
        """
        创建用户
        :param validated_data:
        :return:
        """
        # 删除password2, sms_code, allow
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        # 创建user模型
        user = User.objects.create(**validated_data)
        # user = super().create(validated_data)
        # 给密码加密
        user.set_password(validated_data['password'])

        user.save()

        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 保存进返回给前端user中
        user.token = token
        return user
